
import React from 'react';
import PageTitle from 'component/page-title/index.js';
import CategorSelector from './category-selector.js';

import FileUploader from 'util/file-upload/image-upload.js';
import RichEditor from 'util/rich-editor/rich-editor.js';

import  './save.scss';

import MUtil from 'util/mm.js';
import Product from 'servers/product-server.js';

import { Link } from 'react-router-dom';

const _product = new Product();
const _mm = new MUtil();

class ProductSave extends React.Component {
    constructor(props){
        super(props);
        this.state={
            name                : '',
            subtitle            : '',
            categoryId          : 0,
            parentCategoryId    : 0,
            subImages           : [],
            price               : '',
            stock               : '',
            detail              : '',
            status              : 1  //商品状态1为在售

        }
    }
    //简单的字段的改变，比如 商品 的描述 价格 库存
    onValueChange(e){
        let name   = e.target.name,
            value  = e.target.value.trim();
            this.setState({
                [name]:value
            })
    }

    // 获取子集组件品类的的选着
    onCategoryChange(categoryId, parentCategoryId){
        this.setState({
            categoryId       : categoryId,
            parentCategoryId : parentCategoryId
        }); 

    }
    // 上传图片成功
    onUploadsuccess(res){ 
        let subImages =  this.state.subImages;
        subImages.push(res);
        this.setState({
            subImages : subImages 
        });
    }
    // 上传图片 失败
    onUploaderror(errMsg){
        _mm.errorTips(errMsg);
    }
    // 删除图片
    onImageDelect(e){
        // 首先要 先获取 index的值 好知道要删除那个图片
        let index = parseInt(e.target.getAttribute('index')),
            subImages = this.state.subImages;
            // 下面我们要删除subImages 下对应的图片
            
           subImages.splice(index,1);
           this.setState({
               subImages:subImages
           })
    }
    // 富文本编辑器的变化
    onDetailValueChange(value){
        console.log(value);
        this.setState({
            detail:value
        })
    }
    getSubImagesString(){
        return this.state.subImages.map((image)=>image.uri).join(',');
    }
    // 提交表单
    onSubmint(){
        let product = {
            name       : this.state.name, 
            subtitle   : this.state.subtitle,
            categoryId : parseInt(this.state.categoryId),
            subImages  : this.getSubImagesString(),
            detail     : this.state.detail,
            price      :  parseFloat(this.state.price),
            stock      :  parseInt(this.state.stock),
            status     : this.state.status
           
        },
        productCheckResult = _product.checkProduct(product);
        // 表单验证成功
        if(productCheckResult.status){
            _product.saveProduct(product).then((res)=>{
                _mm.successTips(res);
                this.props.history.push('/product/index');
            },(errMsg)=>{
                _mm.errorTips(errMsg);
            });
        }else{
            // 表单验证失败
            _mm.errorTips(productCheckResult.msg);
        }
    }
    render() {
        return (
            <div id="page-wrapper">
                <PageTitle title="商品添加页面">
                    <div className="page-header-right">
                        <Link to="/product/" className="btn btn-primary">
                            <i className="fa fa-plus"></i>
                            <span>取消</span>
                       </Link>  
                    </div>   
                </PageTitle>
                <div className="form-horizontal">
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品名称</label>
                        <div className="col-md-5">
                        <input type="text" className="form-control" 
                        name="name"
                        onChange={(e)=>this.onValueChange(e)}
                        placeholder="商品名称"/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label  className="col-md-2 control-label">商品描述</label>
                        <div className="col-md-6">
                        <input type="text" className="form-control"
                        name="subtitle"
                        onChange={(e)=>this.onValueChange(e)}
                        placeholder="商品描述"/>
                        </div>
                    </div>

                    <div className="form-group">
                        <label  className="col-md-2 control-label">商品分类</label>
                        <CategorSelector onCategoryChange={
                            (categoryId,parentCategoryId) => this.onCategoryChange(categoryId,parentCategoryId)
                        }/> 
                    </div>

                    <div className="form-group">
                        <label  className="col-md-2 control-label">商品价格</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control"
                                name="price"
                                onChange={(e)=>this.onValueChange(e)}
                                placeholder="商品价格"/>
                                <span className="input-group-addon">$</span>
                            </div>
                        </div>
                    </div>

                    <div className="form-group">
                        <label  className="col-md-2 control-label">商品库存</label>
                        <div className="col-md-3">
                        <div className="input-group">
                            <input type="number" className="form-control"
                            name="stock"
                            onChange={(e)=>this.onValueChange(e)}
                            placeholder="商品库存"/>
                            <span className="input-group-addon" >件</span>
                        </div>
                        </div>
                    </div>

                    <div className="form-group">
                        <label  className="col-md-2 control-label">商品图片</label>
                        <div className="col-md-10">
                        {/* 这里存放图片 */}
                             {
                                 this.state.subImages.length ? this.state.subImages.map(
                                    (image,index)=>(
                                        <div className="img-con"  key={index}>
                                            <img src={image.url} className="img"/>
                                        <i className="fa fa-close" index={index} onClick={(e)=>this.onImageDelect(e)}></i>
                                        </div>
                                    )
                                    
                                 ):(<div>请上传图片</div> )

                             }
                        </div>
                        <div className="col-md-offset-2 col-md-10 margin-top">
                            <FileUploader onSuccess={(res)=>this.onUploadsuccess(res)}
                            onError={(errMsg)=>this.onUploaderror(errMsg)}
                            />  
                        </div>
                    </div>

                    <div className="form-group">
                        <label  className="col-md-2 control-label">商品内容编辑</label>
                        <div className="col-md-10">
                        <RichEditor onValueChange={(value) =>this.onDetailValueChange(value)}/> 
                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-md-offset-2 col-md-10">
                            <button type="submit" className="btn btn-primary" onClick={(e)=>{this.onSubmint()}}>提交</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
export default ProductSave